<template>
    <div>
        <div v-show="activeStatu">
            <el-card class="box">
                <div style="padding: 10px">
                    <!-- 搜索名称或标题 -->
                    <div class="flex">
                        <div style="width: 220px">店铺名称</div>
                        <div class="time_top">上架/下架</div>
                    </div>
                    <div class="flexBox">
                        <div> <el-input v-model.trim="ruleFormtwo.title" placeholder="输入内容" style="width: 220px">
                                <template #prefix>
                                    <el-icon class="el-input__icon">
                                        <search />
                                    </el-icon>
                                </template>
                            </el-input>
                        </div>
                        <div style="margin-left: 20px;">
                            <el-select v-model="value" @change="ange_indexof" clearable placeholder="请选择"
                                style="width: 240px">
                                <el-option v-for="item in options" :label="item.label" :value="item.value" />
                            </el-select>
                        </div>

                    </div>
                    <!-- 表格数据渲染 -->
                    <div> <el-table :data="filteredData.slice((currentPage - 1) * pageSize, currentPage * pageSize)"
                            style="margin-top: 10px;width: 100%;" :cell-style="{ 'text-align': 'center' }"
                            :header-cell-style="{ 'text-align': 'center' }" @selection-change="handleTableScroll">
                            <el-table-column type="selection" fixed="left" />
                            <el-table-column prop="id" width="80" label="序号" fixed="left" />
                            <el-table-column prop="title" label="店铺名称" show-overflow-tooltip width="200" />
                            <el-table-column prop="" label="店铺状态" width="120">
                                <template #default="scope">
                                    <div class="handle">
                                        <el-switch
                                            :model-value="scope.row.status == 1 ? true : scope.row.status == 2 ? false : scope.row.status"
                                            inline-prompt @click="funstatus(scope.row)" />
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column prop="info" label="介绍" center show-overflow-tooltip width="200" />
                            <el-table-column prop="img" label="海报" width="100">
                                <template #default="scope">
                                    <div>
                                        <el-image style="width: 40px; height: 40px"
                                            :src="scope.row.img.startsWith(testName) ? scope.row.img : testName + scope.row.img"
                                            :zoom-rate="1.2" :max-scale="7" :min-scale="0.2"
                                            :preview-src-list="[scope.row.img.startsWith(testName) ? scope.row.img : testName + scope.row.img]"
                                            :initial-index="4" fit="cover" preview-teleported />
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column prop="createtime" label="营业时间" width="170">
                                <template #default="scope">
                                    <div>{{ scope.row.starttime }}-{{ scope.row.endtime }}</div>
                                </template>
                            </el-table-column>
                            <el-table-column prop="quantity" width="120" sortable label="销量" />
                            <el-table-column prop="createtime" label="创建时间" width="170" />
                            <el-table-column label="操作" width="120" fixed="right">
                                <template #default="scope">
                                    <div class="handle">
                                        <div @click="edit(scope.row)"
                                            style="color: rgba(64, 158, 255, 1);cursor: pointer">编辑</div>
                                    </div>
                                </template>
                            </el-table-column>
                        </el-table></div>
                    <div class="paging">
                        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                            :page-sizes="[5, 10, 20, 50]" :small="small" :disabled="disabled" background
                            layout="total, sizes, prev, pager, next, jumper" :total="filteredData.length" />
                    </div>
                    <!-- 删除弹窗 -->
                    <el-dialog title="删除" v-model="centerDialogVisible" width="30%" center>
                        <div style="font-size: 16px; padding-bottom: 20px">确认删除该数据吗?</div>
                        <div style="display: flex; justify-content: end">
                            <el-button @click="centerDialogVisible = false">取 消</el-button>
                            <el-button type="primary" @click="deleteid">确 定</el-button>
                        </div>
                    </el-dialog>
                </div>
                <el-dialog v-model="shows" title="是否要删除" center width="20vw">
                    <el-button @click="shows = false">取 消</el-button>
                    <el-button type="primary" @click="oks">确 定</el-button>
                </el-dialog>
                <!-- 批量删除 -->
                <el-dialog title="批量删除" v-model="centerDialogVisiblet" width="30%" center>
                    <div style="font-size: 16px">确认删除这批数据吗?</div>
                    <span slot="footer" style="display: flex; justify-content: space-between" class="dialog-footer">
                        <div></div>
                        <div>
                            <el-button @click="centerDialogVisiblet = false">取 消</el-button>
                            <el-button type="primary" @click="deleteid_t">确 定</el-button>
                        </div>
                    </span>
                </el-dialog>
            </el-card>

        </div>


        <!-- 第二块 -->
        <div v-show="activeStatud" style="padding: 10px">
            <el-card
                style="width: 96%;margin-left: 2%;margin-top: 1%;position: relative;height: auto;padding-bottom:50px">
                <div style="padding: 10px">编辑</div>
                <div style="width:94%;height: 1px; background-color: rgba(195, 195, 195, 1);"></div>
                <div style="margin-top: 20px; margin-left: 100px;padding-botton:10px">
                    <el-form ref="ruleFormRef" style="wizdth:90%" :model="ruleForm" status-icon :rules="rules"
                        label-position="left" label-width="auto" class="demo-ruleForm">
                        <div style="display: flex;width: 90%;justify-content: space-between;">
                            <div style="width: 48%;">
                                <el-form-item label="店铺名称" prop="title" style="width: 90%">
                                    <el-input v-model.trim="ruleForm.title" placeholder="请输入" style="width: 90%" />
                                </el-form-item>
                                <el-form-item label="店铺类型" prop="foodtype_id" style="width: 90%">
                                    <el-select v-model="ruleForm.foodtype_id" placeholder="请选择" style="width: 90%"
                                        clearable multiple>
                                        <el-option v-for="item in optionss" :key="item.value" :label="item.label"
                                            :value="item.value" />
                                    </el-select>
                                </el-form-item>
                                <el-form-item label="店铺评分" prop="score" style="width: 90%">
                                    <el-rate v-model="ruleForm.score" allow-half style="width: 90%" />
                                </el-form-item>
                                <el-form-item label="店铺电话" prop="tel" style="width: 90%">
                                    <el-input v-model.number="ruleForm.tel" placeholder="请输入" style="width: 90%"
                                        type="number" @input="ruleForm.tel = $event.replace(/[^\d]/g, '')"
                                        maxlength="11" pattern="\d{11}" />
                                </el-form-item>
                                <el-form-item label="开始营业时间" prop="starttime" style="width: 90%">
                                    <el-time-picker v-model="ruleForm.starttime" placeholder="请选择开始营业时间"
                                        style="width: 90%" format="h:mm:ss a" value-format="HH:mm:ss" :picker-options="{
                                            selectableRange: '00:00:00 - 23:59:59',
                                            showMeridian: true
                                        }" />
                                </el-form-item>
                                <el-form-item label="结束营业时间" prop="endtime" style="width: 90%">
                                    <el-time-picker v-model="ruleForm.endtime" placeholder="请选择结束营业时间"
                                        style="width: 90%" format="h:mm:ss a" value-format="HH:mm:ss" :picker-options="{
                                            selectableRange: '00:00:00 - 23:59:59',
                                            showMeridian: true
                                        }" />
                                </el-form-item>
                                <el-form-item label="店铺公告" prop="notice" style="width: 90%">
                                    <el-input v-model.trim="ruleForm.notice" placeholder="请输入" style="width: 90%" />
                                </el-form-item>
                                <el-form-item label="店铺标签" prop="label" style="width: 90%">
                                    <el-input v-model.trim="ruleForm.label" placeholder="请输入" style="width: 90%" />
                                </el-form-item>
                                <!-- 单图封面图片 -->
                                <el-form-item prop="img" label="商品封面">
                                    <el-upload list-type="picture-card" accept=".jpeg,.png,.jpg,.bmp,.gif"
                                        :on-preview="handlePictureCardPreviewt" :on-change="handleChange"
                                        :on-remove="handleRemovet" :file-list="fileListt"
                                        :before-upload="beforeAvatarUploadt">
                                        <el-icon>
                                            <Plus />
                                        </el-icon>
                                    </el-upload>
                                </el-form-item>
                                <el-form-item prop="status" label="上架下架" style="margin-top: 15px">
                                    <el-switch v-model="ruleForm.status" />
                                </el-form-item>
                            </div>
                            <div style="width: 48%;">
                                <!-- 多图片上传   -->
                                <el-form-item label="商品介绍" prop="info" style="width: 90%">
                                    <el-input v-model.trim="ruleForm.info" maxlength="200" style="width:90%"
                                        placeholder="Please input" show-word-limit type="textarea"
                                        :autosize="{ minRows: 3, maxRows: 5 }" />
                                </el-form-item>
                                <el-form-item style="margin-top: 50px;" prop="imgs" label="商品轮播">
                                    <el-upload class="custom-upload" list-type="picture-card"
                                        accept=".jpeg,.png,.jpg,.bmp,.gif" :on-exceed="exceed_li"
                                        :on-preview="handlePictureCardPreview" :on-remove="handleRemove"
                                        :file-list="fileList" :on-change="handleChanges" :before-upload="beforeUpload"
                                        :auto-upload="false" :limit="4">
                                        <el-icon>
                                            <Plus />
                                        </el-icon>
                                    </el-upload>
                                </el-form-item>
                                <el-form-item label="经度" prop="longitude" style="width: 90%">
                                    <el-input v-model.trim="ruleForm.longitude" placeholder="请输入" style="width: 90%" />
                                </el-form-item>
                                <el-form-item label="维度" prop="latitude" style="width: 90%">
                                    <el-input v-model.trim="ruleForm.latitude" placeholder="请输入" style="width: 90%" />
                                </el-form-item>
                                <el-form-item label="店铺地址" prop="" style="width: 90%">
                                    <div style="width: 90%;display: flex;align-items: center;">
                                        <el-input id="tipinput" v-model.trim="searchKeyword" placeholder="请输入关键字"
                                            clearable style="width: 50%" />
                                        <el-button type="primary" style="margin-left: 10px;"
                                            @click="searchs">搜索</el-button>
                                    </div>
                                    <div id="container" style="width: 90%; height: 200px;margin-top: 60px;"></div>
                                </el-form-item>
                            </div>
                        </div>
                    </el-form>
                    <div class="dialog-footer" style="margin-top:100px;margin-left:70%">
                        <el-button type="primary" @click="submitForm(ruleFormRef)">确认</el-button>
                        <el-button @click="closes(ruleFormRef)" style="margin-left: 30px;">取消</el-button>
                    </div>
                </div>
            </el-card>
        </div>
        <el-dialog v-model="dialogVisible">
            <img style="width: 90%; height: 90%" w-full :src="dialogImageUrl" alt="Preview Image" />
        </el-dialog>
        <el-dialog v-model="dialogVisiblet">
            <img style="width: 90%; height: 90%" w-full :src="dialogImageUrlt" alt="Preview Image" />
        </el-dialog>
    </div>
</template>
<script setup lang="ts">
import { ref, reactive, onUpdated, computed } from 'vue';
import { ElMessage, ElCard } from 'element-plus';
import { scenicUpload } from '../../../api/uploading/index';
import { food_shopList, food_shopSave } from '../../../api/foodShop/index';
import { foodList } from '../../../api/food/index';
import { inject } from 'vue'
const dialogVisible = ref(false);
const optionss = ref([])
// 地图引入
// 引入高德地图API
import { load } from "@amap/amap-jsapi-loader";
// 用户输入的地点关键字
const searchKeyword = ref("");
let map = null; //初始化地图
let placeSearch = null; // 声明placeSearch变量
let lati = ref('');
let longi = ref('');
onUpdated(async () => {
    // 设置高德地图的安全配置【此处一定要配置，否则会搜索失败】
    window._AMapSecurityConfig = {
        securityJsCode: "34068d35a8585449adcfdfc5b28b5006",
    };
    // 初始化地图
    map = await initMap();
    // 加载插件并绑定事件
    ({ placeSearch } = await loadPluginsAndBindEvents(map)); // 返回并解构出placeSearch
});
// 初始化高德地图实例
async function initMap() {
    // 加载高德地图API，包括指定的版本和插件
    const defaultCenter = [113.85, 35.30];
    const AMap = await load({
        key: "635f2e7ebbd699fa68ef6fad1494f713", // 高德地图API Key
        version: "2.0",
        plugins: ["AMap.PlaceSearch", "AMap.AutoComplete"],
        zoom: 10,
        center: [longi.value, lati.value]
    });
    // 创建地图实例，设置容器ID和允许自适应窗口大小
    return new AMap.Map("container", {
        resizeEnable: true,
        viewMode: "2D",
        zoom: 11,
        center: longi.value && lati.value
            ? [parseFloat(longi.value), parseFloat(lati.value)]
            : defaultCenter,
    });
}
// 加载插件并绑定事件
async function loadPluginsAndBindEvents(map) {
    const autoOptions = {
        input: "tipinput", //绑定到输入框的ID
    };
    // 创建自动完成实例
    const auto = new AMap.AutoComplete(autoOptions);
    // 创建地点搜索实例，关联到地图
    const ps = new AMap.PlaceSearch({
        map: map,
    });
    // 绑定自动完成的选中事件，根据选中的地点设置城市并执行搜索
    auto.on("select", (e) => {
        ps.setCity(e.poi.adcode); //设置搜索城市为选中地点的城市编码
        ps.search(e.poi.name); //搜索选中地点的名称
    });
    // 地图点标记
    map.on('click', function (e) {
        ruleForm.latitude = e.lnglat.getLng();
        ruleForm.longitude = e.lnglat.getLat();
    });
    if (longi.value && lati.value) {
        const marker = new AMap.Marker({
            position: [parseFloat(longi.value), parseFloat(lati.value)],
        });
        map.add(marker);
    }
    return { placeSearch: ps }; // 返回placeSearch实例
}
// 点击搜索
const searchs = () => {
    // 判断用户是否输入了关键字
    if (!searchKeyword.value.trim()) {
        ElMessage.error("请输入搜索内容！");
        return;
    }
    // 执行地点搜索，并处理搜索结果
    placeSearch.search(searchKeyword.value, (status, result) => {
        console.log(status, result);
        console.log(result.poiList.pois[0].location.lat);
        ruleForm.longitude = result.poiList.pois[0].location.lat
        ruleForm.latitude = result.poiList.pois[0].location.lng

        if (status === "complete" && result.info === "OK") {
            // 如果搜索成功且有搜索结果
            if (result.poiList.pois.length > 0) {
                // 取第一个搜索结果，设置地图中心和缩放级别
                const poi = result.poiList.pois[0];
                map.setCenter([poi.location.lng, poi.location.lat]);
                map.setZoom(15); //缩放级别
            } else {
                ElMessage.error("未找到相关地点！");
            }
        } else {
            ElMessage.error("搜索失败！");
        }
    });
}
let tokens = JSON.parse(localStorage.getItem('tokens'));
console.log(tokens);
// 创建数据变量
const activeList = ref([]);
const activeStatu = ref(true)
const activeStatud = ref(false)
const testFn = inject('testFn')
testFn()
const testName = inject('testName')
console.log(testName);
const dialogTableVisible = ref(false);
const statused = ref('1');

// ---------------表格页码数-------------------------
const pageSize = ref(5);
const currentPage = ref(1);
const copyList = ref([]);
const files = ref(false);

// 验证文件类型
const validateFileType = (fileType) => {
    return ['.jpg', '.png', '.jpeg', '.bmp', '.gif'].includes(fileType.toLowerCase())
}
// 上传图片返回路径
const fileImg = ref([])
const fileList = ref([])
// 图片移除
const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
    console.log('移除文件:', uploadFile);

    // 获取要删除的图片的相对路径
    const fileUrl = uploadFile.url;
    const relativePath = fileUrl.startsWith(testName)
        ? fileUrl.replace(testName, '')
        : fileUrl;

    // 从 uploadedImages 中移除对应的路径
    if (uploadedImages.value.includes(relativePath)) {
        uploadedImages.value = uploadedImages.value.filter(path => path !== relativePath);
    }

    // 更新 ruleForm.imgs
    ruleForm.imgs = uploadedImages.value.join(',');

    // 更新 fileList
    fileList.value = uploadFiles.map(file => ({
        name: file.name,
        url: file.url
    }));

    if (uploadFiles.length < 1) {
        ruleForm.imgs = '';
    }
};
const dialogImageUrl = ref('')
const dialogVisiblet = ref(false)
const dialogImageUrlt = ref('')
// 图片放大视图
const handlePictureCardPreview = (file) => {
    // console.log(file.raw.name);
    dialogImageUrl.value = file.url;
    dialogVisible.value = true;
}
// 图片超出限制
const exceed_li = () => {
    ElMessage({
        message: '最多可上传四张',
        type: 'warning',
    })
}
// 图片上传回调函数
// 图片上传回调函数 - 处理单图上传（商品封面）
const handleChange = (file, fileLists) => {
    const fileName = file.name
    const fileType = fileName.substring(fileName.lastIndexOf('.'))

    // 验证文件类型
    if (!validateFileType(fileType)) {
        ElMessage.error('请上传正确的图片类型（jpeg、png、jpg、bmp、gif）')
        return false
    }

    const formData = new FormData()
    formData.append('file', file.raw)

    scenicUpload(formData).then(res => {
        console.log('单图上传结果:', res)
        if (res.code == 1) {
            const imageUrl = res.data.url
            // 更新封面图片
            ruleForm.img = imageUrl
            fileImg.value = [imageUrl]  // 重置为当前上传的图片
            fileListt.value = [{ url: testName + imageUrl }]  // 更新预览列表
            console.log('封面图片已更新:', imageUrl)
        } else if (res.code == 0) {
            ElMessage.error('图片不能大于2MB!')
            // 从fileLists中移除该文件
            removeFileFromList(fileLists, file)
        }
    })
}

// 多图片上传
const handleChanges = (file, fileLists) => {
    const fileName = file.name;
    const fileType = fileName.substring(fileName.lastIndexOf('.'));

    // 验证文件类型
    if (!validateFileType(fileType)) {
        ElMessage.error('请上传正确的图片类型（jpeg、png、jpg、bmp、gif）');
        return false;
    }

    const formData = new FormData();
    formData.append('file', file.raw);

    scenicUpload(formData).then(res => {
        if (res.code == 1) {
            // 使用接口返回的服务器相对路径（url）
            const serverPath = res.data.url;

            // 确保只添加新图片，不重复添加已删除的图片
            if (!uploadedImages.value.includes(serverPath)) {
                uploadedImages.value.push(serverPath);
            }

            // 更新 ruleForm.imgs（逗号分隔的相对路径）
            ruleForm.imgs = uploadedImages.value.join(',');

            // 更新 fileList 显示（预览用完整 URL）
            fileList.value = uploadedImages.value.map(path => ({
                name: path.split('/').pop(),
                url: testName + path // 显示时拼接域名
            }));

            ElMessage.success('上传成功');
        } else {
            ElMessage.error(res.msg || '上传失败');
            removeFileFromList(fileLists, file); // 移除失败的文件
        }
    }).catch(error => {
        ElMessage.error('上传异常: ' + error.message);
        removeFileFromList(fileLists, file);
    });
};
// 图片上传
const beforeUpload = (rawFile) => {
    console.log(rawFile);
    console.log(1);
    if (rawFile.type !== 'image/jpeg') {
        ElMessage.error('Avatar picture must be JPG format!')

        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('Avatar picture size can not exceed 2MB!')

        return false
    }
    return true
}
const fileListt = ref([]);
const handlePictureCardPreviewt = (file) => {
    dialogImageUrlt.value = file.url;
    dialogVisiblet.value = true;
}
// 图片移除
const handleRemovet = (file, fileListt) => {
    console.log(file, fileListt);
    if (fileListt.length < 1) {
        ruleForm.covers = ''
    }
};

// 图片上传回调事件
const beforeAvatarUploadt = (file) => {
    const fileName = file.name
    const fileType = fileName.substring(fileName.lastIndexOf('.'))
    // jpeg,.png,.jpg,.bmp,.gif
    if (
        fileType === '.jpg' ||
        fileType === '.png' ||
        fileType === '.jpeg' ||
        fileType === '.bmp' ||
        fileType === '.gif'
    ) {
    } else {
        ElMessage.error('不是,jpeg,.png,.jpg,.bmp,.gif文件,请上传正确的图片类型')
        return false
    }
    console.log(file);
    // 压缩图片
    compressImage(file).then(compressedBlob => {
        const formData = new FormData();
        formData.append('file', compressedBlob, file.name);
        if (file.size / 1024 / 1024 > 2) {
            console.log(file.size / 1024 / 1024);
            ElMessage.error('图片不能大于2MB!')
            return false
        } else {
            console.log(formData);
            scenicUpload(formData).then(res => {
                console.log(res);
                // 上传时不拼接域名
                const imageUrl = res.data.url;
                fileListt.value = [{
                    // 显示时拼接域名
                    url: testName + imageUrl,
                }]
                ruleForm.covers = imageUrl
            })
        }
    });
    return false; // 阻止默认上传行为
}

const compressImage = (file) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    return new Promise((resolve) => {
        reader.onload = e => {
            const img = new Image();
            img.src = e.target.result;
            img.onload = () => {
                const canvas = document.createElement('canvas');
                const ctx = canvas.getContext('2d');
                const { width, height } = img;
                canvas.width = width;
                canvas.height = height;
                ctx.drawImage(img, 0, 0, width, height);
                const quality = 0.7; // 压缩质量
                const newImageData = canvas.toDataURL('image/jpeg', quality);
            };
        };
    });
};
// 定义搜索条件状态
const searchQuery = ref('');
// 搜索
const ruleFormtwo = reactive({
    title: "",
    state: "",
});
const filteredData = computed(() => {
    return activeList.value.filter(item => {
        const matchesTitle = !ruleFormtwo.title || item.title.includes(ruleFormtwo.title);
        const statuS = !ruleFormtwo.state || item.status.includes(ruleFormtwo.state);
        return matchesTitle && statuS;
    });
});
// ------------------上下架搜索-----------------------
const options = [
    {
        value: '1',
        label: '上架',
    }, {
        value: '0',
        label: '下架'
    }]
render();
// 修改render函数，支持带搜索条件的刷新
function render() {
    // 先保存当前的搜索条件
    const currentQuery = searchQuery.value;

    // 获取店铺列表数据
    food_shopList({
        token: tokens.token,
        uid: tokens.userinfo.id
    }, {
        userid: tokens.userinfo.id
    }).then((res) => {
        console.log(res);
        activeList.value = res.data;
        copyList.value = res.data;

        // 重新应用搜索过滤
        if (currentQuery) {
            applySearchFilter();
        }
    });

    // 获取分类数据（不受搜索影响）
    foodList().then((res) => {
        console.log(res);
        const y = res.data.map(item => ({
            label: item.title,
            value: item.id
        }));
        optionss.value = y;
    });
}
// 上下架搜索
const ange_indexof = (e) => {
    console.log(e);
    if (e == undefined) {
        render()
    }
    let a = [];
    activeList.value = copyList.value.filter(function (item) {
        // 判断是否满足搜索条件
        if (String(item.status).indexOf(String(e)) > -1) {
            return activeList;
        }
    });
    currentPage.value = 1
}
// 上下架
let statust = ref('');
//------------------------ 修改状态切换函数---------------------------
function funstatus(e) {
    console.log(e);

    Object.assign(ruleForm, e);
    console.log(e);

    if (e.status == 0) {
        ruleForm.status = 1;
    } else {
        ruleForm.status = 0;
    }

    food_shopSave(ruleForm).then((res) => {
        if (res.code == '1') {
            ElMessage({
                message: '操作成功',
                type: 'success',
            });
            setTimeout(() => {
                activeStatud.value = false;
                activeStatu.value = true;
                fileList.value = [];
            }, 1200);

            // 刷新列表时保留搜索条件
            render(searchQuery.value);
        } else {
            ElMessage({
                message: '编辑失败，不能和原数据一致',
                type: 'warning',
            });
        }
    });
}

// 表单对象
const ruleForm = reactive({
    id: '',
    foodtype_id: '',
    title: '',
    score: '',
    money: '',
    quantity: '',
    starttime: '',
    endtime: '',
    status: '',
    img: '',
    imgs: [],
    notice: '',
    longitude: '',
    latitude: '',
    label: '',
    tel: '',
    info: '',
    users_id: '',
    createtime: '',
    updatetime: '',
    uid: tokens.userinfo.id
});

// 表单
const ruleFormRef = ref('');
const rules = reactive({

    tiele: [
        { required: true, message: '请填写名称', trigger: 'blur' },
    ],
    score: [
        { required: true, message: '请填写评分', trigger: 'blur' },
    ],
    money: [
        { required: true, message: '请填写价格', trigger: 'blur' },
        { type: 'number', message: '请输入数字', trigger: 'blur' },
    ],
    quantity: [
        { required: true, message: '请填写库存', trigger: 'blur' },
        { type: 'number', message: '请输入数字', trigger: 'blur' },
        { min: 0, message: '库存不能小于0', trigger: 'blur' },
    ],
    starttime: [
        { required: true, message: '请填写开始时间', trigger: 'blur' },
    ],
    endtime: [
        { required: true, message: '请填写结束时间', trigger: 'blur' },

    ],
    status: [
        {
            required: true, message: '请选择状态', trigger: 'change'
        }],
    notice: [
        { required: true, message: '请填写特色', trigger: 'blur' },
    ],
    longitude: [
        { required: true, message: '请填写经度', trigger: 'blur' },

    ],
    latitude: [
        { required: true, message: '请填写纬度', trigger: 'blur' },

    ],
    label: [
        { required: true, message: '请填写标签', trigger: 'blur' },
    ],
    tel: [
        { required: true, message: '请填写电话', trigger: 'blur' },
    ],
    info: [
        { required: true, message: '请填写简介', trigger: 'blur' },
    ],
    users_id: [
        { required: true, message: '请选择所属商家', trigger: 'change' },
    ],
    img: [
        { required: true, message: '请上传图片', trigger: 'blur' },
    ],
    imgs: [
        { required: true, message: '请上传轮播', trigger: 'blur' },
    ],

});

const imgUrls = ref('');
// 已上传的图片URL数组
const uploadedImages = ref([])
// 点击确认或编辑确定
// 修改 submitForm 方法
const submitForm = (formEl) => {
    if (!formEl) return;
    formEl.validate((valid) => {
        if (valid) {
            if (statused.value == '2') {
                // 准备提交数据
                const submitData = {
                    ...ruleForm,
                    foodtype_id: Array.isArray(ruleForm.foodtype_id)
                        ? ruleForm.foodtype_id.join(',')
                        : '',
                    status: ruleForm.status ? '1' : '0',
                    // 处理图片 - 确保提交的是相对路径
                    img: fileListt.value.length > 0
                        ? fileListt.value[0].url.replace(testName, '')
                        : '',
                    imgs: fileList.value
                        .map(item => item.url.replace(testName, ''))
                        .join(',')
                };

                console.log('提交数据:', submitData);

                food_shopSave(submitData).then((res) => {
                    console.log(res);

                    if (res.code == '1') {
                        ElMessage.success('编辑成功');
                        setTimeout(() => {
                            activeStatud.value = false;
                            activeStatu.value = true;
                            fileList.value = [];
                            fileListt.value = [];
                        }, 1200);
                        render();
                    } else {
                        ElMessage.warning(res.msg || '编辑失败');
                    }
                }).catch(err => {
                    ElMessage.error('请求失败: ' + err.message);
                });
            }
        } else {
            ElMessage.error('请填写完整表单');
        }
    });
};

// 添加计算属性显示当前选中的类型名称
const selectedTypeNames = computed(() => {
    if (!ruleForm.foodtype_id || !optionss.value) return '';

    return ruleForm.foodtype_id
        .map(id => {
            const found = optionss.value.find(item => item.value == id);
            return found ? found.label : '';
        })
        .filter(name => name)
        .join(', ');
});
// 关闭新增
const closes = (formEl) => {
    console.log(formEl);
    activeStatu.value = true
    activeStatud.value = false
    formEl.resetFields();
    formEl.clearValidate()
    dialogTableVisible.value = false;
    files.value = false;
    ruleForm.name = ''
    fileList.value = []
    fileListt.value = []

};
// 添加缺失的 handleTableScroll 方法
const handleTableScroll = () => {
    console.log('Table scrolled');
};
// 点击编辑
// edit 方法
function edit(item) {
    // 重置表单
    Object.assign(ruleForm, {
        id: '',
        foodtype_id: [],
        title: '',
        score: '',
        money: '',
        quantity: '',
        starttime: '',
        endtime: '',
        status: false,
        img: '',
        imgs: '',
        notice: '',
        longitude: '',
        latitude: '',
        label: '',
        tel: '',
        info: '',
        users_id: '',
        createtime: '',
        updatetime: '',
        uid: tokens.userinfo.id
    });
    lati.value = item.latitude;
    longi.value = item.longitude;
    console.log(lati.value);
    // 重新初始化地图以应用新坐标
    initMap().then(newMap => {
        map = newMap;
        loadPluginsAndBindEvents(map);
    });
    // 填充表单数据
    Object.assign(ruleForm, item);

    // 特殊处理 foodtype_id
    if (item.foodtype_id) {
        ruleForm.foodtype_id = item.foodtype_id
            .split(',')
            .map(id => parseInt(id.trim()))
            .filter(id => !isNaN(id));
    } else {
        ruleForm.foodtype_id = [];
    }

    // 处理状态
    ruleForm.status = item.status == 1;

    // 处理封面图片
    if (item.img) {
        // 过滤掉 blob 临时地址
        if (!item.img.startsWith('blob:')) {
            const coverUrl = item.img.startsWith('http') ? item.img : testName + item.img;
            fileListt.value = [{
                name: item.img.split('/').pop(),
                url: coverUrl
            }];
            // 存储原始路径（不带域名）
            ruleForm.img = item.img.startsWith('http')
                ? item.img.replace(testName, '')
                : item.img;
        }
    }

    // 处理多图 - 修改后的逻辑
    if (item.imgs) {
        // 过滤掉 blob 临时地址
        const validImgUrls = item.imgs.split(',').filter(img => !img.startsWith('blob:'));

        fileList.value = validImgUrls.map(img => {
            const fullUrl = img.startsWith('http') ? img : testName + img;
            return {
                name: img.split('/').pop(),
                url: fullUrl
            };
        });

        // 存储原始路径（不带域名）
        uploadedImages.value = validImgUrls.map(img =>
            img.startsWith('http') ? img.replace(testName, '') : img
        );
        ruleForm.imgs = uploadedImages.value.join(',');
    }

    // 显示编辑面板
    activeStatud.value = true;
    activeStatu.value = false;
    statused.value = '2';
}
</script>

<style>
/* 你的样式 */
@import url("https://cache.amap.com/lbs/static/main1119.css");

.text {
    font-size: 14px;
}

.item {
    margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
    display: table;
    content: '';
}

.clearfix:after {
    clear: both;
}

.box-card {
    display: flex;
    height: 300px;
    width: 90%;
}

.el-popper {
    max-width: 30%;
    padding-bottom: 5px !important;
    display: -webkit-box;
    overflow: hidden;
    text-overflow: ellipsis;
    -webkit-line-clamp: 15;
    -webkit-box-orient: vertical;

}

.el-popper,
.el-popper is-dark {
    /* background: rgb(48, 65, 86) !important; */
    color: #fff !important;
    line-height: 24px;
}

.handle {
    display: flex;
    align-items: center;
    justify-content: center;
}

.paging {
    display: flex;
    justify-content: center;
    margin-top: 10px;
    height: 70px;
}

.flex {
    display: flex;
    align-items: center;
    padding-bottom: 10px;
}

.flexBox {
    display: flex;
    width: 100%;
    align-items: center;
}

.el-upload-list--picture-card {
    --el-upload-list-picture-card-size: 100px;
    display: inline-flex;
    flex-wrap: wrap;
    margin: 0;
}

.el-upload--picture-card {
    --el-upload-picture-card-size: 99px;
    align-items: center;
    background-color: var(--el-fill-color-lighter);
    border: 1px dashed var(--el-border-color-darker);
    border-radius: 6px;
    box-sizing: border-box;
    cursor: pointer;
    display: inline-flex;
    height: var(--el-upload-picture-card-size);
    justify-content: center;
    vertical-align: top;
    width: var(--el-upload-picture-card-size);
}

/* 自定义上传组件样式 */
.custom-upload {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    max-width: 350px;
}

/* 设置每个上传项的固定大小 */
.custom-upload .el-upload,
.custom-upload .el-upload-list__item {
    width: 100px;
    /* 固定宽度 */
    height: 100px;
    /* 固定高度 */
    margin-bottom: 10px;
    /* 行间距 */
}

/* 确保每行最多显示3个元素 */
.custom-upload .el-upload-list__item:nth-child(3n+1) {
    clear: left;
    /* 每3个元素强制换行 */
}

/* 上传按钮样式 */
.custom-upload .el-upload--picture-card {
    order: 999;
    /* 将上传按钮放在最后 */
}

/* 当有3个或更多图片时，确保上传按钮正确显示 */
.custom-upload .el-upload-list__item:nth-child(3)~.el-upload--picture-card {
    clear: left;
    /* 当有3个图片时，上传按钮换行显示 */
}
</style>